package logic

import (
	"context"
	"fmt"
	"zhihu/models/cache"
	"zhihu/models/mysql"
	"zhihu/pkg"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type PasswordUpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewPasswordUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PasswordUpdateLogic {
	return &PasswordUpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *PasswordUpdateLogic) PasswordUpdate(in *zhihurpc.PasswordUpdateRequest) (*zhihurpc.PasswordUpdateResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前用户不存在，禁止修改密码")
	}
	get := cache.RedisDB.Get(l.ctx, "sendSms"+in.Mobile)
	if get.Val() != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误，请重新输入")
	}
	if in.NewPassword != in.NewsPassword {
		return nil, fmt.Errorf("两次密码输入不一致，请重新输入")
	}
	user.Password = pkg.Md5(in.NewPassword)
	err := mysql.DB.Debug().Updates(&user).Error
	if err != nil {
		return nil, fmt.Errorf("密码修改失败")
	}
	return &zhihurpc.PasswordUpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
